
package com.shop.cloud.mall.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.cloud.common.core.constant.CommonConstants;
import com.shop.cloud.common.core.constant.SecurityConstants;
import com.shop.cloud.common.core.util.R;
import com.shop.cloud.common.data.tenant.TenantContextHolder;
import com.shop.cloud.common.log.annotation.SysLog;
import com.shop.cloud.common.security.annotation.Inside;
import com.shop.cloud.mall.admin.mapper.ShopInfo2Mapper;
import com.shop.cloud.mall.admin.service.ShopDepositConfigService;
import com.shop.cloud.mall.admin.service.ShopDepositService;
import com.shop.cloud.mall.admin.service.UserCollectService;
import com.shop.cloud.mall.common.constant.MallConstants;
import com.shop.cloud.mall.common.entity.ShopDeposit;
import com.shop.cloud.mall.common.entity.ShopDepositConfig;
import com.shop.cloud.mall.common.entity.ShopInfo;
import com.shop.cloud.mall.admin.service.ShopInfoService;
import com.shop.cloud.mall.common.entity.UserCollect;
import com.shop.cloud.upms.common.entity.SysTenantPackage;
import com.shop.cloud.upms.common.feign.FeignTenantService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

/**
 * 店铺表
 *
 * @author
 * @date 2020-05-15 13:35:18
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/shopinfo")
@Tag(description = "shopinfo", name = "店铺表管理")
public class ShopInfoController {

    private final ShopInfoService shopInfoService;
	private final UserCollectService userCollectService;
	private final ShopInfo2Mapper shopInfo2Mapper;
	private final ShopDepositConfigService shopDepositConfigService;
	private final ShopDepositService shopDepositService;
	private final FeignTenantService feignTenantService;

	/**
	 * list查询
	 * @param shopInfo 商城用户
	 * @return
	 */
	@Operation(summary = "list查询")
	@GetMapping("/list")
	public R getList(ShopInfo shopInfo) {
		return R.ok(shopInfoService.list(Wrappers.query(shopInfo).lambda()
				.select(ShopInfo::getId,
						ShopInfo::getName,
						ShopInfo::getImgUrl)));
	}

    /**
     * 分页列表
     * @param page 分页对象
     * @param shopInfo 店铺表
     * @return
     */
    @Operation(summary = "分页列表")
    @GetMapping("/page")
    @PreAuthorize("@ato.hasAuthority('mall:shopinfo:index')")
    public R getPage(Page page, ShopInfo shopInfo) {
        return R.ok(shopInfoService.page1(page, Wrappers.query(shopInfo)));
    }

    /**
     * 店铺表查询
     * @param id
     * @return R
     */
    @Operation(summary = "店铺表查询")
    @GetMapping("/{id}")
    @PreAuthorize("@ato.hasAuthority('mall:shopinfo:get','mall:orderinfo:edit')")
    public R getById(@PathVariable("id") String id) {
		ShopInfo shopInfo = shopInfoService.getById(id);
		long count = userCollectService.count(Wrappers.<UserCollect>lambdaQuery()
				.eq(UserCollect::getRelationId,shopInfo.getId()));
		shopInfo.setCollectCount((int)count);
        return R.ok(shopInfo);
    }

    /**
     * 店铺表新增
     * @param shopInfo 店铺表
     * @return R
     */
    @Operation(summary = "店铺表新增")
    @SysLog("新增店铺表")
    @PostMapping
    @PreAuthorize("@ato.hasAuthority('mall:shopinfo:add')")
    public R save(@RequestBody ShopInfo shopInfo) {
		long count = shopInfoService.count();
		if(count >= 1){
			//单店模式只能新增一个店铺
			SysTenantPackage sysTenantPackage = feignTenantService.getTenantPackage(TenantContextHolder.getTenantId(), SecurityConstants.FROM_IN).getData();
			if(sysTenantPackage == null){
				return R.failed("您的商城未开通套餐");
			}
			if(CommonConstants.MALL_MODE_1.equals(sysTenantPackage.getMallMode())){
				return R.failed("单店模式套餐不能开多个店铺");
			}
		}
        return R.ok(shopInfoService.save(shopInfo));
    }

    /**
     * 店铺表修改
     * @param shopInfo 店铺表
     * @return R
     */
    @Operation(summary = "店铺表修改")
    @SysLog("修改店铺表")
    @PutMapping
    @PreAuthorize("@ato.hasAuthority('mall:shopinfo:edit')")
    public R updateById(@RequestBody ShopInfo shopInfo) {
		shopInfo.setServiceFee(null);
		shopInfo.setEnable(null);
		shopInfo.setSaleType(null);
        return R.ok(shopInfoService.updateById(shopInfo));
    }

    /**
     * 店铺表删除
     * @param id
     * @return R
     */
    @Operation(summary = "店铺表删除")
    @SysLog("删除店铺表")
    @DeleteMapping("/{id}")
    @PreAuthorize("@ato.hasAuthority('mall:shopinfo:del')")
    public R removeById(@PathVariable String id) {
        return R.ok(shopInfoService.removeById(id));
    }

	/**
	 * 数量查询
	 * @param shopInfo 店铺
	 * @return
	 */
	@Operation(summary = "数量查询")
	@GetMapping("/count")
	public R getCount(ShopInfo shopInfo) {
		if(StrUtil.isNotBlank(shopInfo.getTenantId())){
			TenantContextHolder.setTenantId(shopInfo.getTenantId());
		}
		long count = shopInfo2Mapper.selectCount(Wrappers.query(shopInfo));
		TenantContextHolder.clear();
		return R.ok(count);
	}

	/**
	 * 更新店铺AliAuthToken
	 * @param id
	 * @return
	 */
	@Operation(summary = "更新店铺AliAuthToken")
	@Inside
	@PutMapping("/aliauthtoken/{id}/{aliAuthToken}")
	Boolean updateAliAuthTokenInside(@PathVariable("id") String id, @PathVariable("aliAuthToken") String aliAuthToken){
		ShopInfo shopInfo = new ShopInfo();
		shopInfo.setId(id);
		shopInfo.setAliAuthToken(aliAuthToken);
		return shopInfoService.updateById(shopInfo);
	}

	/**
	 * 更新店铺wxMchId
	 * @param id
	 * @return
	 */
	@Operation(summary = "更新店铺wxMchId")
	@Inside
	@PutMapping("/wxmchid/{id}/{wxMchId}")
	Boolean updateWxMchIdInside(@PathVariable("id") String id, @PathVariable("wxMchId") String wxMchId){
		ShopInfo shopInfo = new ShopInfo();
		shopInfo.setId(id);
		shopInfo.setWxMchId(wxMchId);
		return shopInfoService.updateById(shopInfo);
	}

	/**
	 * 店铺服务费修改
	 * @param shopInfo 店铺
	 * @return R
	 */
	@Operation(summary = "店铺服务费修改")
	@SysLog("店铺服务费修改")
	@PutMapping("/servicefee")
	@PreAuthorize("@ato.hasAuthority('mall:shopinfo:edit:servicefee')")
	public R updateServiceFeeById(@RequestBody ShopInfo shopInfo) {
		ShopInfo shopInfo2 = new ShopInfo();
		shopInfo2.setId(shopInfo.getId());
		shopInfo2.setServiceFee(shopInfo.getServiceFee());
		return R.ok(shopInfoService.updateById(shopInfo));
	}

	/**
	 * 店铺表查询
	 * @param id
	 * @return R
	 */
	@Operation(summary = "店铺表查询")
	@GetMapping("/inside/{id}")
	@Inside
	public R getByIdInside(@PathVariable("id") String id) {
		ShopInfo shopInfo = shopInfoService.getById(id);
		return R.ok(shopInfo);
	}

	/**
	 * 店铺数量
	 * @return R
	 */
	@Operation(summary = "店铺数量")
	@PostMapping("/inside/count")
	@Inside
	public R getCountInside(ShopInfo shopInfo) {
		return R.ok(shopInfoService.count(Wrappers.query(shopInfo)));
	}

	/**
	 * 开户、关闭店铺
	 * @param shopInfo 店铺
	 * @return R
	 */
	@Operation(summary = "开户、关闭店铺")
	@SysLog("开户、关闭店铺")
	@PutMapping("/enable")
	@PreAuthorize("@ato.hasAuthority('mall:shopinfo:edit:enable')")
	public R updateEnableById(@RequestBody ShopInfo shopInfo) {
		ShopInfo shopInfo2 = new ShopInfo();
		shopInfo2.setId(shopInfo.getId());
		shopInfo2.setEnable(shopInfo.getEnable());
		if(CommonConstants.YES.equals(shopInfo.getEnable())){
			//校验保证金
			ShopDepositConfig shopDepositConfig = shopDepositConfigService.getOne(Wrappers.emptyWrapper());
			if(shopDepositConfig != null && CommonConstants.YES.equals(shopDepositConfig.getEnable())){
				//已开启保证金，校验该店铺是否已缴纳
				long count = shopDepositService.count(Wrappers.<ShopDeposit>query().lambda()
						.eq(ShopDeposit::getStatus, MallConstants.SHOP_DEPOSIT_STATUS_1)
						.eq(ShopDeposit::getIsPay,CommonConstants.YES)
						.eq(ShopDeposit::getShopId, shopInfo.getId()));
				if(count <= 0){
					return R.failed("开启失败！店铺未缴纳保证金");
				}
			}
		}
		return R.ok(shopInfoService.updateById(shopInfo));
	}
}
